package cn.qyd.threadsignal;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 邱运铎
 * @date 2024-03-25 12:32
 */
public class CyclicBarrierDemo01 {
    static class PreTask implements Runnable {
        private CyclicBarrier cyclicBarrier;
        private String task;

        public PreTask(String task, CyclicBarrier cyclicBarrier) {
            this.task = task;
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            Random random = new Random();
            for (int i = 0; i < 4; i++) {
                try {
                    Thread.sleep(random.nextInt(3000));
                    System.out.println(String.format("关卡-%d-的--%s--任务已完成", i, task));
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
            System.out.println("当前关卡所有资源已经加载完成。开始进入下一关卡，");
        });
        System.out.println("开始玩游戏。");
        new Thread(new PreTask("加载地图模型",cyclicBarrier)).start();
        new Thread(new PreTask("加载人物模型",cyclicBarrier)).start();
        new Thread(new PreTask("加载背景音乐",cyclicBarrier)).start();

        //因为是idea,在启动程序，idea会多启动一个线程，所以判断数量为2，其他的只需要判断1个，就是主线程main
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println("已经没有下一个关卡了，游戏通关！！！");
    }
}
